<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">管理员登录</h2>

      <el-form :model="loginForm" :rules="loginRules" @keyup.enter="handleLogin" label-position="left"
        label-width="70px" class="login-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入管理员用户名" prefix-icon="User" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password />
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <div class="captcha-container">
            <el-input v-model="loginForm.code" placeholder="请输入验证码" prefix-icon="uuid" class="captcha-input" />
            <div class="captcha-image" @click="refreshCaptcha" :style="{ backgroundImage: captchaImageUrl ? `url(${captchaImageUrl})` : 'none', backgroundSize: 'cover' }"></div>
          </div>
        </el-form-item>

        <el-form-item class="login-btn-item">
          <el-button type="primary" :loading="loading" @click="handleLogin" class="login-button">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { adminLogin, getAdminCaptcha } from '@/api/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 生成UUID函数
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// 表单数据
const loginForm = ref({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

// 加载状态
const loading = ref(false)

// 验证码图片 URL
const captchaImageUrl = ref('')

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

// 刷新验证码
const refreshCaptcha = () => {
  const uuid = generateUUID(); // 生成一个唯一的UUID
  loginForm.value.uuid = uuid;

  getAdminCaptcha(uuid).then(res => {
    const codeBase64 = res.data.codeBase64
    captchaImageUrl.value = `data:image/png;base64,${codeBase64}`
  }).catch(error => {
    console.error('获取验证码失败:', error)
  })
}

// 登录处理
const handleLogin = () => {
  loading.value = true
  console.log('登录表单数据:', loginForm.value)
  
  // 请求后端的管理员登录接口
  adminLogin({
    username: loginForm.value.username,
    password: loginForm.value.password,
    uuid: loginForm.value.uuid,
    code: loginForm.value.code
  }).then(res => { 
    loading.value = false
    if (res.code === 200) {
      ElMessage.success('登录成功')
      
      // 保存管理员信息
      const adminInfo = {
        userId: res.data.Admin.userId,
        username: res.data.Admin.username,
        role: 'admin'
      };
      
      sessionStorage.setItem("userInfo", JSON.stringify(adminInfo))
      sessionStorage.setItem("token", res.data.token || res.token)
      router.push('/main')
    } else {
      ElMessage.error(res.message || '登录失败')
      console.error('登录失败:', res.message)
      refreshCaptcha() // 刷新验证码
    }
  }).catch(error => {
    loading.value = false
    ElMessage.error('登录失败，请检查网络连接')
    console.error('登录失败:', error)
    refreshCaptcha() // 刷新验证码
  })
}

// 钩子函数
onMounted(() => {
  refreshCaptcha();
})
</script>

<style lang="scss" scoped>
.login-container {
  background-image: url('/public/background-img2.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  margin-left: auto;
  margin-right: 120px;
  width: 380px;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.95);
}

.login-title {
  text-align: center;
  margin-bottom: 35px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.login-button {
  width: 100%;
  margin-top: 20px;
  height: 40px;
  font-size: 16px;
}

.captcha-container {
  display: flex;
  align-items: center;
  // gap: 1px;
}

.captcha-input {
  flex: 1;
  min-width: 140px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  background-color: #f5f7fa;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    opacity: 0.8;
  }
}

.login-form {
  .el-form-item {
    margin-bottom: 25px;
  }
}

:deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding-right: 12px;
}

:deep(.el-input__wrapper) {
  padding: 0 12px;
  height: 40px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;

  &:hover {
    box-shadow: 0 0 0 1px #c0c4cc inset;
  }

  &.is-focus {
    box-shadow: 0 0 0 1px #409EFF inset;
  }
}

:deep(.el-input__prefix) {
  color: #909399;
}

.login-btn-item {
  margin-bottom: 0 !important;
  margin-top: 30px;
}
</style>